﻿<%@ Page Language="C#" AutoEventWireup="true" EnableSessionState="True" %>

<%@ Register TagPrefix="Hi" Namespace="Hidistro.UI.SaleSystem.Tags" Assembly="Hidistro.UI.SaleSystem.Tags" %>
<%@ Register TagPrefix="Hi" Namespace="Hidistro.UI.Common.Controls" Assembly="Hidistro.UI.Common.Controls" %>
<%@ Register TagPrefix="wnxd" Namespace="wnxd.web" Assembly="wnxd.web" %>
<%@ Import Namespace="Hidistro.Entities.Sales" %>
<%@ Import Namespace="Hidistro.SaleSystem.Shopping" %>
<%@ Import Namespace="Hidistro.Entities.Orders" %>
<%@ Import Namespace="Hidistro.Messages" %>
<%@ Import Namespace="Hidistro.Membership.Context" %>
<%@ Import Namespace="Hidistro.Core" %>
<%@ Import Namespace="Hidistro.Membership.Core" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="Hidistro.Entities" %>
<%@ Import Namespace="wnxd.javascript" %>
<%@ Import Namespace="Hidistro.SqlDal.Sales" %>
<script runat="server">
    private bool IsMobilePhone(string input)
    {
        Regex regex = new Regex("^1[23456798][0-9]{9}$");
        return regex.IsMatch(input);
    } 
    protected json Post()
    {
        json json = new json(new { error = -1 });
        int region;
        if (!int.TryParse(Request.Form["regionSelectorValue"], out region) || region == 0)
        {
            json["msg"] = "请选择收货地址";
            return json;
        }
        string pattern = @"[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5_a-zA-Z0-9]*";
        Regex regex = new Regex(pattern);
        if (!(!string.IsNullOrEmpty(Request.Form["shr"]) && regex.IsMatch(Request.Form["shr"].Trim())))
        {
            json["msg"] = "请输入正确的收货人姓名";
            return json;
        }
        if ((Request.Form["shr"].Length < 2) || (Request.Form["shr"].Length > 20))
        {
            json["msg"] = "收货人姓名长度应在2-20个字符之间";
            return json;
        }
        if (string.IsNullOrEmpty(Request.Form["shdz"]))
        {
            json["msg"] = "请输入收货人详细地址";
            return json;
        }
        if (string.IsNullOrEmpty(Request.Form["sjhm"]) || !IsMobilePhone(Request.Form["sjhm"]))
        {
            json["msg"] = "请输入正确的手机号码";
            return json;
        }
        string[] sku = this.Request.Form["product"].Split(',');
        ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(sku[0], 1, true);

        if (sku.Length > 1)
        {

            ShoppingCartItemInfo item = new ShoppingCartDao().GetCartItemInfo(HiContext.Current.User as Member, sku[1], 1);
            shoppingCart.LineItems.Add(item);
        }
        decimal nub = 0;
        string[] arr = sku[0].Split('_');
        //if (arr.Length > 1 && !string.IsNullOrEmpty(arr[2]))
        //{
        //    if (arr[2] == "1048")
        //    {

        //        nub = 40;
        //    }
        //    if (arr[2] == "1049")
        //    {

        //        nub = 60;
        //    }
        //} 
        
        if (this.Page.Request.Form["fkfs"] != "1")
        {
            shoppingCart.ReducedPromotionAmount = shoppingCart.LineItems[0].AdjustedPrice * 0.08m+nub;
            shoppingCart.IsReduced = true;
        }
        else
        {
            shoppingCart.ReducedPromotionAmount = nub;
            shoppingCart.IsReduced = true;
        }
        OrderInfo orderInfo = GetOrderInfo(shoppingCart);


        string source = null;
        HttpCookie cookie = HttpContext.Current.Request.Cookies["Source"];
        if (cookie != null) source = cookie.Value;
        else
            source = Request.Form["source"];
        if (ShoppingProcessor.CreatOrder(orderInfo, source))
        {
            Messenger.OrderCreated(orderInfo, HiContext.Current.User);
            orderInfo.OnCreated();
            json["error"] = 0;
            json["url"] = "/Vshop/FinishOrder.aspx?orderId=" + orderInfo.OrderId;
        }
        else
        {
            json["msg"] = "购买失败";
        }
        return json;
    }
    private OrderInfo GetOrderInfo(ShoppingCartInfo shoppingCartInfo)
    {
        OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(shoppingCartInfo, false, false, true);
        if (orderInfo == null)
        {
            return null;
        }
        orderInfo.OrderId = this.GenerateOrderId();
        orderInfo.OrderDate = DateTime.Now;
        IUser user = HiContext.Current.User;
        orderInfo.UserId = user.UserId;
        orderInfo.Username = user.Username;
        orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
        orderInfo.RefundStatus = RefundStatus.None;
        FillOrderShippingMode(orderInfo, shoppingCartInfo);
        FillOrderPaymentMode(orderInfo);
        orderInfo.OrderSource = OrderSource.Wap;
        return orderInfo;
    }
    private void FillOrderShippingMode(OrderInfo orderInfo, ShoppingCartInfo shoppingCartInfo)
    {
        orderInfo.Address = Globals.HtmlEncode(Request.Form["shdz"]);
        orderInfo.ShipTo = Globals.HtmlEncode(Request.Form["shr"]);
        orderInfo.CellPhone = Request.Form["sjhm"];
        orderInfo.ShippingModeId = int.Parse("2", NumberStyles.None);
        int region;
        if (int.TryParse(Request.Form["regionSelectorValue"], out region))
        {
            orderInfo.RegionId = region;
            orderInfo.ShippingRegion = RegionHelper.GetFullRegion(region, "，");
        }
        orderInfo.ShipToDate = "时间不限";
        ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(orderInfo.ShippingModeId, true);
        if (shippingMode != null)
        {
            orderInfo.ShippingModeId = shippingMode.ModeId;
            orderInfo.ModeName = shippingMode.Name;
            if (!(shoppingCartInfo.IsFreightFree || ((shoppingCartInfo.LineItems.Count<ShoppingCartItemInfo>(a => !a.IsfreeShipping) <= 0) && (shoppingCartInfo.LineGifts.Count <= 0))))
            {
                orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, shoppingCartInfo.Weight, shippingMode);
            }
            else
            {
                orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
            }
        }
    }
    private void FillOrderPaymentMode(OrderInfo orderInfo)
    {
        orderInfo.PaymentTypeId = int.Parse(Request.Form["fkfs"]);
        PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(orderInfo.PaymentTypeId);
        if (paymentMode != null)
        {
            orderInfo.PaymentType = Globals.HtmlEncode(paymentMode.Name);
            orderInfo.PayCharge = ShoppingProcessor.CalcPayCharge(orderInfo.GetTotal(), paymentMode);
            orderInfo.Gateway = paymentMode.Gateway;
        }
    }
    private string GenerateOrderId()
    {
        string str = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 7; i++)
        {
            int num = random.Next();
            str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
        }
        int v = random.Next(0, 9);
        return (DateTime.Now.ToString("yyyyMMdd") + str + v);
    }
</script>
<wnxd:web runat="server"></wnxd:web>
